<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小学二年级数学速算比赛</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .main-content {
            padding: 30px;
        }

        .nav-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
            border-bottom: 2px solid #f0f0f0;
            flex-wrap: wrap;
        }

        .nav-tab {
            padding: 12px 24px;
            background: transparent;
            border: none;
            cursor: pointer;
            font-size: 1.1em;
            color: #666;
            border-bottom: 3px solid transparent;
            transition: all 0.3s;
            position: relative;
            top: 2px;
        }

        .nav-tab:hover {
            color: #667eea;
        }

        .nav-tab.active {
            color: #667eea;
            border-bottom-color: #667eea;
            font-weight: bold;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .game-mode {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .mode-card {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            padding: 25px;
            border-radius: 15px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            border: 2px solid transparent;
        }

        .mode-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
            border-color: #667eea;
        }

        .mode-card h3 {
            font-size: 1.5em;
            margin-bottom: 10px;
            color: #667eea;
        }

        .mode-card p {
            color: #666;
            line-height: 1.6;
        }

        .rules-box {
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            padding: 30px;
            border-radius: 15px;
            border-left: 5px solid #667eea;
            line-height: 1.8;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .rules-box h3 {
            color: #667eea;
            margin-bottom: 20px;
            font-size: 1.5em;
            text-align: center;
            padding-bottom: 15px;
            border-bottom: 2px solid #e0e0e0;
        }

        .rules-box ul {
            list-style: none;
            padding-left: 0;
        }

        .rules-box li {
            padding: 15px;
            padding-left: 50px;
            margin-bottom: 12px;
            position: relative;
            background: white;
            border-radius: 8px;
            border-left: 3px solid transparent;
            transition: all 0.3s;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
        }

        .rules-box li:hover {
            border-left-color: #667eea;
            transform: translateX(5px);
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
        }

        .rules-box li:before {
            content: "✓";
            position: absolute;
            left: 15px;
            top: 15px;
            color: white;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            width: 28px;
            height: 28px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 0.9em;
        }

        .rules-box li strong {
            color: #667eea;
            font-size: 1.05em;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .header h1 {
                font-size: 1.8em;
            }

            .main-content {
                padding: 20px;
            }

            .nav-tabs {
                flex-direction: column;
            }

            .nav-tab {
                width: 100%;
                text-align: left;
                border-bottom: 1px solid #eee;
                border-left: 3px solid transparent;
                top: 0;
            }

            .nav-tab.active {
                border-left-color: #667eea;
                border-bottom-color: #eee;
            }

            .game-mode {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 480px) {
            body {
                padding: 10px;
            }

            .header {
                padding: 20px;
            }

            .header h1 {
                font-size: 1.5em;
            }

            .main-content {
                padding: 15px;
            }
        }

        /* 游戏界面样式 */
        .game-screen {
            display: none;
        }

        .game-screen.active {
            display: block;
        }

        .game-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .game-info {
            display: flex;
            gap: 30px;
            flex-wrap: wrap;
        }

        .info-item {
            text-align: center;
        }

        .info-item label {
            display: block;
            font-size: 0.9em;
            color: #666;
            margin-bottom: 5px;
        }

        .info-item .value {
            font-size: 1.5em;
            font-weight: bold;
            color: #667eea;
        }

        .timer {
            font-size: 2em;
            font-weight: bold;
            color: #e74c3c;
        }

        .question-box {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px;
            border-radius: 15px;
            text-align: center;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .question-number {
            font-size: 1em;
            opacity: 0.9;
            margin-bottom: 10px;
        }

        .question-text {
            font-size: 2.5em;
            font-weight: bold;
            margin: 20px 0;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
        }

        .answer-input-box {
            margin: 30px 0;
        }

        .answer-input {
            width: 100%;
            max-width: 300px;
            padding: 20px;
            font-size: 2em;
            text-align: center;
            border: 3px solid #ddd;
            border-radius: 10px;
            outline: none;
            transition: all 0.3s;
        }

        .answer-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 10px rgba(102, 126, 234, 0.3);
        }

        @keyframes pulse {
            0%, 100% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.05);
            }
        }

        .submit-btn {
            padding: 15px 40px;
            font-size: 1.2em;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: bold;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 7px 20px rgba(0, 0, 0, 0.3);
        }

        .submit-btn:active {
            transform: translateY(0);
        }

        .submit-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .btn-back {
            padding: 10px 20px;
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-bottom: 20px;
        }

        .btn-back:hover {
            background: #5a6268;
        }

        /* 成绩记录样式 */
        .result-card {
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
        }

        .result-card:hover {
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
            transform: translateY(-2px);
        }

        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
            flex-wrap: wrap;
            gap: 10px;
        }

        .result-title {
            font-size: 1.3em;
            font-weight: bold;
            color: #667eea;
        }

        .result-date {
            color: #999;
            font-size: 0.9em;
        }

        .result-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }

        .stat-item {
            text-align: center;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 8px;
        }

        .stat-label {
            font-size: 0.85em;
            color: #666;
            margin-bottom: 5px;
        }

        .stat-value {
            font-size: 1.3em;
            font-weight: bold;
            color: #667eea;
        }

        .stat-value.correct {
            color: #28a745;
        }

        .stat-value.accuracy {
            color: #ffc107;
        }

        .result-details-btn {
            padding: 8px 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            font-size: 0.9em;
            transition: all 0.3s;
            width: 100%;
        }

        .result-details-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }

        .question-details {
            display: none;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 2px solid #f0f0f0;
        }

        .question-details.active {
            display: block;
        }

        .question-item {
            padding: 12px;
            margin-bottom: 10px;
            border-radius: 8px;
            border-left: 4px solid #ddd;
            background: #f8f9fa;
        }

        .question-item.correct {
            border-left-color: #28a745;
            background: #f0f9f4;
        }

        .question-item.incorrect {
            border-left-color: #dc3545;
            background: #fff5f5;
        }

        .question-item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            flex-wrap: wrap;
            gap: 5px;
        }

        .question-text-detail {
            font-weight: bold;
            font-size: 1.1em;
            color: #333;
        }

        .question-status {
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 0.85em;
            font-weight: bold;
        }

        .question-status.correct {
            background: #28a745;
            color: white;
        }

        .question-status.incorrect {
            background: #dc3545;
            color: white;
        }

        .question-answer-info {
            font-size: 0.95em;
            color: #666;
            line-height: 1.6;
        }

        .question-explanation {
            margin-top: 8px;
            padding: 8px;
            background: white;
            border-radius: 5px;
            font-size: 0.9em;
            color: #555;
            font-style: italic;
        }

        @media (max-width: 768px) {
            .question-text {
                font-size: 2em;
            }

            .answer-input {
                font-size: 1.5em;
                max-width: 100%;
            }

            .game-header {
                flex-direction: column;
                align-items: stretch;
            }

            .game-info {
                justify-content: space-around;
            }

            .timer {
                font-size: 1.5em;
                text-align: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🧮 小学二年级数学速算比赛</h1>
            <p>提升计算能力，挑战自我极限！</p>
        </div>

        <div class="main-content">
            <!-- 导航标签 -->
            <div class="nav-tabs">
                <button class="nav-tab active" data-tab="home">🏠 首页</button>
                <button class="nav-tab" data-tab="rules">📋 比赛规则</button>
                <button class="nav-tab" data-tab="results">📊 我的成绩</button>
            </div>

            <!-- 首页内容 -->
            <div id="home" class="tab-content active">
                <h2 style="text-align: center; margin-bottom: 30px; color: #667eea;">选择比赛模式</h2>
                <div class="game-mode">
                    <div class="mode-card" onclick="startGame('countdown')">
                        <h3>⏱️ 倒计时比赛</h3>
                        <p>3分钟内尽可能完成更多的题目</p>
                        <p style="margin-top: 10px; font-weight: bold; color: #667eea;">挑战你的速度！</p>
                    </div>
                    <div class="mode-card" onclick="startGame('normal')">
                        <h3>🎯 常规比赛</h3>
                        <p>5分钟内最多完成70道题</p>
                        <p style="margin-top: 10px; font-weight: bold; color: #667eea;">追求准确与速度！</p>
                    </div>
                </div>
            </div>

            <!-- 比赛规则内容 -->
            <div id="rules" class="tab-content">
                <div class="rules-box">
                    <h3>📋 比赛规则说明</h3>
                    <ul>
                        <li><strong>倒计时比赛模式：</strong>比赛时间为3分钟，在时间内尽可能完成更多题目，答题越多得分越高。</li>
                        <li><strong>常规比赛模式：</strong>比赛时间为5分钟，最多完成70道题目，题目做完后可以提前结束。</li>
                        <li><strong>题目类型：</strong>包含100以内的加减法、九九乘法表、除法口诀，以及5道混合运算题。</li>
                        <li><strong>计分规则：</strong>每题答对得1分，答错不得分，系统会自动记录正确率。</li>
                        <li><strong>成绩记录：</strong>每次比赛的成绩都会自动保存，包括完成时间、正确率、详细答题记录。</li>
                        <li><strong>温馨提示：</strong>答题时请仔细计算，既要速度快，也要保证准确率哦！</li>
                    </ul>
                </div>
            </div>

            <!-- 我的成绩内容 -->
            <div id="results" class="tab-content">
                <div class="rules-box">
                    <h3>📊 我的成绩记录</h3>
                    <div id="results-list">
                        <p style="text-align: center; color: #999; padding: 20px;">暂无成绩记录，快去参加比赛吧！</p>
                    </div>
                </div>
            </div>

            <!-- 游戏界面 -->
            <div id="game-screen" class="game-screen">
                <button class="btn-back" onclick="exitGame()">← 返回首页</button>
                <div class="game-header">
                    <div class="game-info">
                        <div class="info-item">
                            <label>题目进度</label>
                            <div class="value"><span id="current-question">0</span> / <span id="total-questions">0</span></div>
                        </div>
                        <div class="info-item">
                            <label>正确题数</label>
                            <div class="value" id="correct-count">0</div>
                        </div>
                        <div class="info-item">
                            <label>已答题数</label>
                            <div class="value" id="answered-count">0</div>
                        </div>
                    </div>
                    <div class="timer" id="timer-display">03:00</div>
                </div>

                <div class="question-box">
                    <div class="question-number">第 <span id="question-index">1</span> 题</div>
                    <div class="question-text" id="question-text">准备开始...</div>
                </div>

                <div style="text-align: center;">
                    <div class="answer-input-box">
                        <input type="number" 
                               id="answer-input" 
                               class="answer-input" 
                               placeholder="请输入答案"
                               autocomplete="off"
                               inputmode="numeric"
                               pattern="[0-9]*">
                    </div>
                    <button class="submit-btn" id="submit-btn" onclick="submitAnswer()">提交答案</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 标签页切换功能
        document.querySelectorAll('.nav-tab').forEach(tab => {
            tab.addEventListener('click', function() {
                const targetTab = this.getAttribute('data-tab');
                
                // 移除所有活动状态
                document.querySelectorAll('.nav-tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
                
                // 激活选中的标签页
                this.classList.add('active');
                document.getElementById(targetTab).classList.add('active');
            });
        });

        // 题目生成逻辑
        // 生成随机整数
        function randomInt(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }

        // 生成100以内的加法题
        function generateAddition() {
            const a = randomInt(1, 50);
            const b = randomInt(1, 100 - a);
            return {
                question: `${a} + ${b} = ?`,
                answer: a + b,
                type: '加法'
            };
        }

        // 生成100以内的减法题
        function generateSubtraction() {
            const a = randomInt(1, 100);
            const b = randomInt(1, a);
            return {
                question: `${a} - ${b} = ?`,
                answer: a - b,
                type: '减法'
            };
        }

        // 生成九九乘法表题目
        function generateMultiplication() {
            const a = randomInt(1, 9);
            const b = randomInt(1, 9);
            return {
                question: `${a} × ${b} = ?`,
                answer: a * b,
                type: '乘法'
            };
        }

        // 生成除法口诀题目
        function generateDivision() {
            const divisor = randomInt(2, 9);
            const quotient = randomInt(1, 9);
            const dividend = divisor * quotient;
            return {
                question: `${dividend} ÷ ${divisor} = ?`,
                answer: quotient,
                type: '除法'
            };
        }

        // 生成混合运算题：加法乘法 (a + b) × c，要求 (a + b) ≤ 9
        function generateAddMultiply() {
            let a, b, c, sum;
            do {
                // 确保 a + b ≤ 9
                a = randomInt(1, 8);
                b = randomInt(1, 9 - a);
                sum = a + b;
                c = randomInt(2, 5);
            } while (sum > 9);
            return {
                question: `(${a} + ${b}) × ${c} = ?`,
                answer: sum * c,
                type: '混合运算-加法乘法',
                explanation: `${a} + ${b} = ${sum}，${sum} × ${c} = ${sum * c}`
            };
        }

        // 生成混合运算题：加法除法 (a + b) ÷ c，要求 (a + b) ≤ 9
        function generateAddDivide() {
            let a, b, c, sum;
            do {
                // 确保 a + b ≤ 9 且能被c整除
                a = randomInt(1, 8);
                b = randomInt(1, 9 - a);
                sum = a + b;
                c = randomInt(2, 6);
            } while (sum > 9 || sum % c !== 0);
            return {
                question: `(${a} + ${b}) ÷ ${c} = ?`,
                answer: sum / c,
                type: '混合运算-加法除法',
                explanation: `${a} + ${b} = ${sum}，${sum} ÷ ${c} = ${sum / c}`
            };
        }

        // 生成混合运算题：减法乘法 (a - b) × c，要求 (a - b) ≤ 9
        function generateSubtractMultiply() {
            // 确保 a - b ≤ 9
            const diff = randomInt(1, 9);
            const b = randomInt(1, 10);
            const a = diff + b; // 确保 a - b = diff ≤ 9
            const c = randomInt(2, 5);
            return {
                question: `(${a} - ${b}) × ${c} = ?`,
                answer: diff * c,
                type: '混合运算-减法乘法',
                explanation: `${a} - ${b} = ${diff}，${diff} × ${c} = ${diff * c}`
            };
        }

        // 生成混合运算题：减法除法 (a - b) ÷ c，要求 (a - b) ≤ 9
        function generateSubtractDivide() {
            let diff, c, b, a;
            do {
                // 确保 a - b ≤ 9 且能被c整除
                diff = randomInt(1, 9);
                c = randomInt(2, 6);
                b = randomInt(1, 10);
                a = diff + b; // 确保 a - b = diff ≤ 9
            } while (diff % c !== 0);
            return {
                question: `(${a} - ${b}) ÷ ${c} = ?`,
                answer: diff / c,
                type: '混合运算-减法除法',
                explanation: `${a} - ${b} = ${diff}，${diff} ÷ ${c} = ${diff / c}`
            };
        }

        // 生成混合运算题：a + b × c（先乘后加）
        function generateNoBracketAddMultiply() {
            const a = randomInt(1, 20);
            const b = randomInt(2, 5);
            const c = randomInt(2, 5);
            const product = b * c;
            return {
                question: `${a} + ${b} × ${c} = ?`,
                answer: a + product,
                type: '混合运算-先乘后加',
                explanation: `先算乘法：${b} × ${c} = ${product}，再算加法：${a} + ${product} = ${a + product}`
            };
        }

        // 生成混合运算题：a + b ÷ c（先除后加）
        function generateNoBracketAddDivide() {
            const a = randomInt(1, 20);
            const b = randomInt(2, 8);
            const c = randomInt(2, 6);
            // 确保b能被c整除
            const quotient = Math.floor(b / c) * c;
            const divided = quotient / c;
            return {
                question: `${a} + ${quotient} ÷ ${c} = ?`,
                answer: a + divided,
                type: '混合运算-先除后加',
                explanation: `先算除法：${quotient} ÷ ${c} = ${divided}，再算加法：${a} + ${divided} = ${a + divided}`
            };
        }

        // 生成混合运算题：a - b × c（先乘后减）
        function generateNoBracketSubtractMultiply() {
            const a = randomInt(10, 30);
            const b = randomInt(2, 5);
            const c = randomInt(2, 5);
            const product = b * c;
            // 确保a大于product，结果为非负
            const finalA = Math.max(a, product + 1);
            return {
                question: `${finalA} - ${b} × ${c} = ?`,
                answer: finalA - product,
                type: '混合运算-先乘后减',
                explanation: `先算乘法：${b} × ${c} = ${product}，再算减法：${finalA} - ${product} = ${finalA - product}`
            };
        }

        // 生成混合运算题：a - b ÷ c（先除后减）
        function generateNoBracketSubtractDivide() {
            const a = randomInt(10, 30);
            const b = randomInt(4, 12);
            const c = randomInt(2, 6);
            // 确保b能被c整除
            const quotient = Math.floor(b / c) * c;
            const divided = quotient / c;
            // 确保a大于divided，结果为非负
            const finalA = Math.max(a, divided + 1);
            return {
                question: `${finalA} - ${quotient} ÷ ${c} = ?`,
                answer: finalA - divided,
                type: '混合运算-先除后减',
                explanation: `先算除法：${quotient} ÷ ${c} = ${divided}，再算减法：${finalA} - ${divided} = ${finalA - divided}`
            };
        }

        // 生成题目列表（包含5道混合运算题）
        function generateQuestions(count) {
            const questions = [];
            const mixedCount = 5; // 必须包含5道混合运算题
            const normalCount = count - mixedCount; // 剩余题目

            // 生成普通题目（加减乘除）
            const normalTypes = [
                generateAddition,
                generateSubtraction,
                generateMultiplication,
                generateDivision
            ];
            
            for (let i = 0; i < normalCount; i++) {
                const typeFunc = normalTypes[randomInt(0, normalTypes.length - 1)];
                questions.push(typeFunc());
            }

            // 生成5道混合运算题（包含带括号和不带括号两种类型）
            // 确保覆盖所有8种类型，优先选择带括号的4种类型，然后是不带括号的4种类型
            const allMixedTypes = [
                generateAddMultiply,              // (a + b) × c
                generateAddDivide,                // (a + b) ÷ c
                generateSubtractMultiply,         // (a - b) × c
                generateSubtractDivide,           // (a - b) ÷ c
                generateNoBracketAddMultiply,      // a + b × c
                generateNoBracketAddDivide,       // a + b ÷ c
                generateNoBracketSubtractMultiply, // a - b × c
                generateNoBracketSubtractDivide   // a - b ÷ c
            ];
            
            // 优先选择前5种类型（包括所有带括号的4种 + 1种不带括号的）
            // 确保至少包含所有4种带括号类型
            const selectedTypes = [
                generateAddMultiply,              // (a + b) × c
                generateAddDivide,                // (a + b) ÷ c
                generateSubtractMultiply,         // (a - b) × c
                generateSubtractDivide,           // (a - b) ÷ c
                allMixedTypes[randomInt(4, 7)]   // 随机选择一种不带括号的类型
            ];
            
            // 打乱选中的类型顺序
            for (let i = selectedTypes.length - 1; i > 0; i--) {
                const j = randomInt(0, i);
                [selectedTypes[i], selectedTypes[j]] = [selectedTypes[j], selectedTypes[i]];
            }
            
            // 生成5道混合运算题
            for (let i = 0; i < mixedCount; i++) {
                questions.push(selectedTypes[i]());
            }

            // 打乱题目顺序
            for (let i = questions.length - 1; i > 0; i--) {
                const j = randomInt(0, i);
                [questions[i], questions[j]] = [questions[j], questions[i]];
            }

            // 为每道题添加序号和用户答案字段
            return questions.map((q, index) => ({
                ...q,
                index: index + 1,
                userAnswer: null,
                isCorrect: false,
                answered: false
            }));
        }

        // 游戏状态管理
        let gameState = {
            mode: null,           // 'countdown' 或 'normal'
            questions: [],        // 题目列表
            currentIndex: 0,      // 当前题目索引
            correctCount: 0,      // 正确答案数
            answeredCount: 0,     // 已答题数
            startTime: null,      // 开始时间
            timer: null,          // 计时器
            timeLeft: 0,          // 剩余时间（秒）
            isPlaying: false      // 是否正在游戏中
        };

        // 开始游戏
        function startGame(mode) {
            if (mode === 'countdown') {
                // 倒计时模式：3分钟
                gameState.mode = 'countdown';
                gameState.timeLeft = 180; // 3分钟 = 180秒
                // 生成足够多的题目（假设最多能做很多题）
                gameState.questions = generateQuestions(100);
            } else if (mode === 'normal') {
                // 常规模式：5分钟，最多70道题
                gameState.mode = 'normal';
                gameState.timeLeft = 300; // 5分钟 = 300秒
                // 生成70道题
                gameState.questions = generateQuestions(70);
            } else {
                return;
            }

            // 重置游戏状态
            gameState.currentIndex = 0;
            gameState.correctCount = 0;
            gameState.answeredCount = 0;
            gameState.startTime = Date.now();
            gameState.isPlaying = true;

            // 隐藏所有标签页内容，显示游戏界面
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.nav-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            document.getElementById('game-screen').classList.add('active');

            // 显示第一题
            showCurrentQuestion();

            // 开始倒计时
            startTimer();

            // 自动聚焦输入框（唤醒键盘）
            setTimeout(() => {
                const input = document.getElementById('answer-input');
                input.focus();
                input.select();
            }, 300);
        }

        // 显示当前题目
        function showCurrentQuestion() {
            // 常规模式下，如果所有题目都答完了，提前结束
            if (gameState.mode === 'normal' && gameState.currentIndex >= gameState.questions.length) {
                endGame();
                return;
            }

            const question = gameState.questions[gameState.currentIndex];
            if (!question) {
                endGame();
                return;
            }

            // 更新题目显示
            document.getElementById('question-index').textContent = question.index;
            document.getElementById('question-text').textContent = question.question;
            
            // 更新进度
            document.getElementById('current-question').textContent = gameState.currentIndex + 1;
            document.getElementById('total-questions').textContent = gameState.questions.length;
            document.getElementById('correct-count').textContent = gameState.correctCount;
            document.getElementById('answered-count').textContent = gameState.answeredCount;

            // 清空输入框
            const input = document.getElementById('answer-input');
            input.value = '';
            input.disabled = false;
            document.getElementById('submit-btn').disabled = false;

            // 自动聚焦输入框
            setTimeout(() => {
                input.focus();
            }, 100);
        }

        // 开始倒计时
        function startTimer() {
            updateTimerDisplay();
            
            gameState.timer = setInterval(() => {
                gameState.timeLeft--;
                updateTimerDisplay();

                // 时间到了
                if (gameState.timeLeft <= 0) {
                    clearInterval(gameState.timer);
                    endGame();
                }
            }, 1000);
        }

        // 更新倒计时显示
        function updateTimerDisplay() {
            const minutes = Math.floor(gameState.timeLeft / 60);
            const seconds = gameState.timeLeft % 60;
            const timeStr = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
            const timerDisplay = document.getElementById('timer-display');
            timerDisplay.textContent = timeStr;

            // 根据模式设置警告时间
            const warningTime = gameState.mode === 'normal' ? 60 : 30; // 常规模式60秒警告，倒计时模式30秒警告
            
            // 最后警告时间显示红色警告
            if (gameState.timeLeft <= warningTime) {
                timerDisplay.style.color = '#e74c3c';
                timerDisplay.style.animation = gameState.timeLeft <= 10 ? 'pulse 0.5s infinite' : 'none';
            } else {
                // 恢复默认颜色
                timerDisplay.style.color = '#e74c3c'; // 默认就是红色，保持不变
                timerDisplay.style.animation = 'none';
            }
        }

        // 提交答案
        function submitAnswer() {
            if (!gameState.isPlaying) return;

            const input = document.getElementById('answer-input');
            const userAnswer = parseInt(input.value);

            // 检查是否输入了答案
            if (isNaN(userAnswer)) {
                alert('请输入答案！');
                input.focus();
                return;
            }

            // 获取当前题目
            const question = gameState.questions[gameState.currentIndex];
            question.userAnswer = userAnswer;
            question.answered = true;

            // 判断是否正确
            question.isCorrect = (userAnswer === question.answer);
            
            if (question.isCorrect) {
                gameState.correctCount++;
            }
            gameState.answeredCount++;

            // 更新显示
            document.getElementById('correct-count').textContent = gameState.correctCount;
            document.getElementById('answered-count').textContent = gameState.answeredCount;

            // 禁用输入和按钮，短暂延迟后进入下一题
            input.disabled = true;
            document.getElementById('submit-btn').disabled = true;

            // 0.8秒后自动进入下一题
            setTimeout(() => {
                gameState.currentIndex++;
                
                // 常规模式下，如果所有题目都答完了，提前结束
                if (gameState.mode === 'normal' && gameState.currentIndex >= gameState.questions.length) {
                    endGame();
                } else {
                    showCurrentQuestion();
                }
            }, 800);
        }

        // 保存成绩到本地存储
        function saveResult() {
            const elapsedTime = Math.floor((Date.now() - gameState.startTime) / 1000);
            const accuracy = gameState.answeredCount > 0 
                ? parseFloat(((gameState.correctCount / gameState.answeredCount) * 100).toFixed(1))
                : 0;

            const result = {
                id: Date.now(),
                mode: gameState.mode === 'countdown' ? '倒计时比赛' : '常规比赛',
                date: new Date().toLocaleString('zh-CN'),
                elapsedTime: elapsedTime,
                timeStr: `${Math.floor(elapsedTime / 60)}分${elapsedTime % 60}秒`,
                totalQuestions: gameState.questions.length,
                answeredCount: gameState.answeredCount,
                correctCount: gameState.correctCount,
                accuracy: accuracy,
                questions: gameState.questions.filter(q => q.answered) // 只保存已答的题目
            };

            // 从localStorage读取现有成绩
            let results = JSON.parse(localStorage.getItem('mathGameResults') || '[]');
            
            // 添加到开头（最新的在前面）
            results.unshift(result);
            
            // 最多保存50条记录
            if (results.length > 50) {
                results = results.slice(0, 50);
            }
            
            // 保存回localStorage
            localStorage.setItem('mathGameResults', JSON.stringify(results));
            
            return result;
        }

        // 结束游戏
        function endGame() {
            gameState.isPlaying = false;
            clearInterval(gameState.timer);

            // 计算完成时间（秒）
            const elapsedTime = Math.floor((Date.now() - gameState.startTime) / 1000);
            const minutes = Math.floor(elapsedTime / 60);
            const seconds = elapsedTime % 60;
            const timeStr = `${minutes}分${seconds}秒`;

            // 计算正确率
            const accuracy = gameState.answeredCount > 0 
                ? ((gameState.correctCount / gameState.answeredCount) * 100).toFixed(1) 
                : 0;

            // 保存成绩
            const result = saveResult();

            // 显示结果
            alert(`比赛结束！\n\n完成时间：${timeStr}\n完成题数：${gameState.answeredCount}题\n正确题数：${gameState.correctCount}题\n正确率：${accuracy}%\n\n成绩已保存，可在"我的成绩"中查看详细记录。`);

            // 返回首页
            exitGame();
            
            // 刷新成绩列表
            loadResults();
        }

        // 退出游戏
        function exitGame() {
            if (gameState.timer) {
                clearInterval(gameState.timer);
                gameState.timer = null;
            }

            gameState.isPlaying = false;

            // 隐藏游戏界面，显示首页
            document.getElementById('game-screen').classList.remove('active');
            document.getElementById('home').classList.add('active');
            document.querySelector('[data-tab="home"]').classList.add('active');
        }

        // 加载并显示成绩列表
        function loadResults() {
            const results = JSON.parse(localStorage.getItem('mathGameResults') || '[]');
            const resultsList = document.getElementById('results-list');
            
            if (results.length === 0) {
                resultsList.innerHTML = '<p style="text-align: center; color: #999; padding: 20px;">暂无成绩记录，快去参加比赛吧！</p>';
                return;
            }

            let html = '';
            results.forEach((result, index) => {
                html += `
                    <div class="result-card">
                        <div class="result-header">
                            <div>
                                <div class="result-title">${result.mode}</div>
                                <div class="result-date">${result.date}</div>
                            </div>
                        </div>
                        <div class="result-stats">
                            <div class="stat-item">
                                <div class="stat-label">完成时间</div>
                                <div class="stat-value">${result.timeStr}</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label">完成题数</div>
                                <div class="stat-value">${result.answeredCount}/${result.totalQuestions}</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label">正确题数</div>
                                <div class="stat-value correct">${result.correctCount}</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-label">正确率</div>
                                <div class="stat-value accuracy">${result.accuracy}%</div>
                            </div>
                        </div>
                        <button class="result-details-btn" onclick="toggleDetails(${result.id})">
                            <span id="btn-text-${result.id}">查看详细记录 ▼</span>
                        </button>
                        <div class="question-details" id="details-${result.id}">
                            ${generateQuestionDetails(result.questions)}
                        </div>
                    </div>
                `;
            });
            
            resultsList.innerHTML = html;
        }

        // 生成题目详细记录HTML
        function generateQuestionDetails(questions) {
            if (!questions || questions.length === 0) {
                return '<p style="text-align: center; color: #999; padding: 10px;">暂无答题记录</p>';
            }

            let html = '';
            questions.forEach((q, index) => {
                const statusClass = q.isCorrect ? 'correct' : 'incorrect';
                const statusText = q.isCorrect ? '✓ 正确' : '✗ 错误';
                const userAnswerText = q.userAnswer !== null ? q.userAnswer : '未答题';
                
                html += `
                    <div class="question-item ${statusClass}">
                        <div class="question-item-header">
                            <div class="question-text-detail">第${index + 1}题：${q.question}</div>
                            <span class="question-status ${statusClass}">${statusText}</span>
                        </div>
                        <div class="question-answer-info">
                            <strong>你的答案：</strong>${userAnswerText} &nbsp;&nbsp;
                            <strong>正确答案：</strong>${q.answer} &nbsp;&nbsp;
                            <strong>题目类型：</strong>${q.type}
                        </div>
                        ${q.explanation ? `<div class="question-explanation">💡 解析：${q.explanation}</div>` : ''}
                    </div>
                `;
            });
            
            return html;
        }

        // 切换详细记录显示/隐藏
        function toggleDetails(resultId) {
            const details = document.getElementById(`details-${resultId}`);
            const btnText = document.getElementById(`btn-text-${resultId}`);
            
            if (details.classList.contains('active')) {
                details.classList.remove('active');
                btnText.textContent = '查看详细记录 ▼';
            } else {
                details.classList.add('active');
                btnText.textContent = '隐藏详细记录 ▲';
            }
        }

        // 添加回车键提交答案功能
        document.addEventListener('DOMContentLoaded', function() {
            const answerInput = document.getElementById('answer-input');
            if (answerInput) {
                answerInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter' && gameState.isPlaying) {
                        e.preventDefault();
                        submitAnswer();
                    }
                });
            }

            // 初始化时加载成绩列表
            loadResults();

            // 当切换到成绩标签页时，刷新成绩列表
            document.querySelector('[data-tab="results"]').addEventListener('click', function() {
                loadResults();
            });
        });
    </script>
</body>
</html>
